package com.gitee.cliveyuan.tools.http;

import com.gitee.cliveyuan.tools.CollectionTools;
import com.gitee.cliveyuan.tools.StringTools;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * Created by clive at 2018/11/26.
 */
class InnerTools {

    /**
     * 将参数追加到url
     *
     * @param url    地址
     * @param params 参数
     */
    static String getQueryUrl(String url, Map<String, String> params) {
        if (CollectionTools.isNotEmpty(params)) {
            String queryStr = StringTools.map2QueryStr(params);
            return url.contains("?") ? url + "&" + queryStr : url + "?" + queryStr;
        }
        return url;
    }

    /**
     * key-value字符串转map
     *
     * @param keyValueStr key-value字符串
     */
    static Map<String, String> keyValueStrToMap(String keyValueStr) {
        Map<String, String> params = Maps.newHashMap();
        if (StringTools.isBlank(keyValueStr)) return params;
        String[] lines = keyValueStr.split("\n");
        for (String line : lines) {
            if (StringTools.isBlank(line)) continue;
            String[] kv = line.split(":");
            if (kv.length > 0) {
                String key = kv[0].trim();
                String value = StringTools.EMPTY;
                if (kv.length > 1) {
                    StringBuilder valueSb = new StringBuilder();
                    for (int i = 1; i < kv.length; i++) {
                        valueSb.append(kv[i].trim());
                        if (kv.length > 2 && i < kv.length - 1)
                            valueSb.append(":");
                    }
                    value = valueSb.toString();
                }
                params.put(key, value);
            }
        }
        return params;
    }
}
